<!-- 在线客服 -->
<template>
  <div class="support-container">
    <!-- 新增顶部导航栏 -->
    <header class="header">
      <img 
        src="@/assets/logo.png" 
        alt="云小脉Logo" 
        class="logo"
      >
      <h1>教育平台客服中心</h1>
      <router-link to="/" class="back-link">返回首页</router-link>
    </header>

    <main class="main-content">
      <div class="chat-box">
        <div class="message-list" ref="messageList">
          <div 
            v-for="(msg, index) in messages"
            :key="index"
            :class="{ 'user-msg': msg.type === 'user' }"
          >
            <div class="message-bubble">
              <span>{{ msg.text }}</span>
              <small class="timestamp">{{ formatTime(msg.timestamp) }}</small>
            </div>
            <div class="status-icon" v-if="msg.status">
              <i 
                :class="`mdi mdi-${msg.status}`" 
                :style="{ color: statusColor(msg.status) }"
              ></i>
            </div>
          </div>
        </div>
        <div class="input-area">
          <textarea 
            v-model="currentMessage"
            placeholder="请输入您的问题..."
            @keyup.enter="sendMessage"
          ></textarea>
          <button @click="sendMessage">发送</button>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import axios from 'axios'

const currentMessage = ref('')
const messages = ref([])
const messageList = ref(null)

async function sendMessage() {
  if (!currentMessage.value.trim()) return

  // 添加用户消息
  const userMessage = currentMessage.value
  messages.value.push({
    type: 'user',
    text: userMessage,
    timestamp: Date.now(),
    status: 'send'
  })
  currentMessage.value = ''
  
  // 立即滚动到底部
  await nextTick()
  messageList.value.scrollTop = messageList.value.scrollHeight

  try {
    // 构造符合DeepSeek API要求的消息历史
    const chatHistory = messages.value.map(msg => ({
      role: msg.type === 'user' ? 'user' : 'assistant',
      content: msg.text
    }))

    const response = await axios.post(
      'https://api.deepseek.com/chat/completions', 
      {
        model: 'deepseek-chat',
        messages: chatHistory,
        temperature: 0.7,
        max_tokens: 2000,
        stream: false
      },
      {
        headers: {
          'Authorization': `Bearer sk-6e5505033651448bb14a87f63933ec1a`,
          'Content-Type': 'application/json'
        },
        timeout: 30000
      }
    )

    // 获取AI回复内容
    const botReply = response.data.choices[0].message.content
    
    // 添加AI回复
    messages.value.push({
      type: 'bot',
      text: botReply,
      timestamp: Date.now(),
      status: 'success'
    })
    
  } catch (error) {
    console.error('API请求失败:', error)
    let errorMessage = '服务暂时不可用，请稍后再试'
    
    if (error.response) {
      // DeepSeek API返回的错误信息
      if (error.response.data?.error?.message) {
        errorMessage = error.response.data.error.message
      } else {
        errorMessage = `服务错误: ${error.response.status} ${error.response.statusText}`
      }
    } else if (error.message.includes('timeout')) {
      errorMessage = '请求超时，请检查网络连接'
    }
    
    messages.value.push({
      type: 'error',
      text: errorMessage,
      timestamp: Date.now(),
      status: 'error'
    })
  }
  
  // 滚动到底部
  await nextTick()
  messageList.value.scrollTop = messageList.value.scrollHeight
}

onMounted(() => {
  messages.value.push({
    type: 'bot',
    text: '欢迎来到教育平台客服中心！我是云小脉，有什么可以帮助您的？',
    timestamp: Date.now(),
    status: 'success'
  })
})

// 时间格式化函数
function formatTime(timestamp) {
  const date = new Date(timestamp)
  return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
}

// 状态图标颜色映射
function statusColor(status) {
  switch (status) {
    case 'send':
      return '#FF6B6B'
    case 'success':
      return '#4CAF50'
    case 'error':
      return '#F44336'
    default:
      return '#CCCCCC'
  }
}
</script>

<style scoped>
.support-container {
  background: linear-gradient(135deg, #48DBFB 0%, #C4E0E5 100%);
  padding: 2rem;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 1.5rem;
  background: linear-gradient(90deg, #007BFF, #6610F2);
  color: white;
  border-radius: 8px 8px 0 0;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  transition: all 0.3s ease;
}

.logo {
  width: 48px;
  height: 48px;
  margin-right: 1rem;
  filter: drop-shadow(0 2px 4px rgba(0,0,0,0.1));
}

.back-link {
  text-decoration: none;
  color: white;
  font-weight: bold;
  position: relative;
  padding-left: 1.5rem;
}

.back-link::before {
  content: "←";
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  font-size: 1.2rem;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  margin-top: 1rem;
  background: #FFFFFF;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.chat-box {
  max-width: 600px;
  margin: auto;
  padding: 2rem;
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 1rem;
  border-radius: 8px;
  background: #F5F5F5;
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.message-bubble {
  display: flex;
  flex-direction: column;
  max-width: 80%;
  word-break: break-word;
  background: #FFFFFF;
  border-radius: 16px;
  padding: 0.75rem 1rem;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.user-msg .message-bubble {
  align-self: flex-end;
  background: #FF6B6B;
  color: white;
  box-shadow: 0 2px 4px rgba(255, 107, 107, 0.5);
}

.timestamp {
  font-size: 0.8rem;
  color: #AAAAAA;
  margin-top: 0.25rem;
  align-self: flex-end;
}

.status-icon {
  margin-left: 0.5rem;
  font-size: 1.2rem;
  color: #AAAAAA;
}

.input-area {
  padding: 1.5rem;
  display: flex;
  gap: 1rem;
  background: #F5F5F5;
  border-radius: 0 0 12px 12px;
}

textarea {
  flex: 1;
  padding: 1rem;
  border: none;
  resize: none;
  border-radius: 8px;
  background: #FFFFFF;
  font-size: 1.1rem;
  outline: none;
  box-shadow: inset 0 0 5px rgba(0,0,0,0.05);
}

button {
  padding: 1rem 1.5rem;
  background: #007BFF;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

button:hover {
  background: #0056b3;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0,0,0,0.15);
}

/* 响应式优化 */
@media (max-width: 768px) {
  .header h1 {
    font-size: 1.2rem;
  }

  .chat-box {
    max-width: 100%;
  }
}
</style>